﻿using System;
using System.Net;
using System.Text;
using Crayon;
using Krilib;

namespace Wassrile.Operation.Web
{
    public static class Connect
    {
        private static NetConnect nc = new NetConnect();

        private static ICredentials GetCredentials()
        {
            return new NetworkCredential(
                Core.Config.account.UserName,
                Core.Config.account.PasswordOrToken);
        }

        public static OperationResult<T> DownloadWithCallback<T>(
            Uri uri,
            bool useIfModifiedSinceHeader,
            bool useCredential,
            NetConnect.DStreamCallback<T> callback,
            string method)
        {
            if (callback == null)
                throw new ArgumentException("callback is null.", "callback");
            return nc.WebConnect<T>(
                uri,
                useIfModifiedSinceHeader,
                method,
                useCredential ? GetCredentials() : null,
                callback);
        }

        public static OperationResult<object> WebPost(
            Uri uri,
            byte[] postData)
        {
            return nc.WebConnect<object>(
                uri,
                true,
                "POST",
                GetCredentials(),
                (NetConnect.DStreamCallback<object>)null,
                postData);
        }

        public static OperationResult<object> WebPostBin(
            Uri uri,
            NetConnect.SendData[] sdArray)
        {
            var req = nc.CreateRequest(uri, true);
            return nc.WebUpload<object>(
                req,
                GetCredentials(),
                (NetConnect.DStreamCallback<object>)null,
                sdArray,
                Encoding.UTF8);
        }

        public static OperationResult<object> WebOperation(Uri uri, string method)
        {
            return nc.WebConnect(
                uri,
                true,
                method,
                GetCredentials()
                );
        }
    }
}
